#region License
/*
The MIT License

Copyright (c) 2008 Sky Morey

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System;
using System.Runtime.InteropServices;
using System.Threading;
using Native_;
using Capture.Utility;
namespace Capture.MME
{
    /// <summary>
    /// Wave Out Buffer
    /// </summary>
    internal class WaveOutBuffer : IDisposable
    {
        public WaveOutBuffer NextBuffer;
        private AutoResetEvent _event = new AutoResetEvent(false);
        private IntPtr _wave;
        private WindowsMultimedia.WaveHdr _header;
        private byte[] _headerData;
        private GCHandle _headerHandle;
        private GCHandle _headerDataHandle;
        private bool _isEnable;

        public WaveOutBuffer(IntPtr waveHandle, int size)
        {
            _wave = waveHandle;
            _headerHandle = GCHandle.Alloc(_header, GCHandleType.Pinned);
            _header.dwUser = (IntPtr)GCHandle.Alloc(this);
            _headerData = new byte[size];
            _headerDataHandle = GCHandle.Alloc(_headerData, GCHandleType.Pinned);
            _header.lpData = _headerDataHandle.AddrOfPinnedObject();
            _header.dwBufferLength = size;
            Helper.Try(WindowsMultimedia.waveOutPrepareHeader(_wave, ref _header, Marshal.SizeOf(_header)));
        }
        ~WaveOutBuffer() { Dispose(); }
        public void Dispose()
        {
            if (_header.lpData != IntPtr.Zero)
            {
                WindowsMultimedia.waveOutUnprepareHeader(_wave, ref _header, Marshal.SizeOf(_header));
                _headerHandle.Free();
                _header.lpData = IntPtr.Zero;
            }
            _event.Close();
            if (_headerDataHandle.IsAllocated)
                _headerDataHandle.Free();
            GC.SuppressFinalize(this);
        }

        internal static void WaveOutProc(IntPtr hdrvr, int uMsg, int dwUser, ref WindowsMultimedia.WaveHdr wavhdr, int dwParam2)
        {
            if (uMsg == WindowsMultimedia.MM_WOM_DONE)
                try
                {
                    var h = (GCHandle)wavhdr.dwUser;
                    var buffer = (WaveOutBuffer)h.Target;
                    buffer.OnCompleted();
                }
                catch { }
        }

        public int Size
        {
            get { return _header.dwBufferLength; }
        }

        public IntPtr Data
        {
            get { return _header.lpData; }
        }

        public bool Play()
        {
            lock (this)
            {
                _event.Reset();
                _isEnable = (WindowsMultimedia.waveOutWrite(_wave, ref _header, Marshal.SizeOf(_header)) == WindowsMultimedia.MMSYSERR_NOERROR);
                return _isEnable;
            }
        }

        public void WaitFor()
        {
            if (_isEnable)
                _isEnable = _event.WaitOne();
            else
                Thread.Sleep(0);
        }

        public void OnCompleted()
        {
            _event.Set();
            _isEnable = false;
        }
    }
}
